import React from 'react';
import {connect} from 'dva';

import SelectField from './selectField'
import SelectTable from './selectTable'
import SelectFieldForConditions from './selectFieldForConditions'

const namespace = "generateXml";


@connect((state) => {
    return {
        tables: state[namespace].tables,
        fieldsMap: state[namespace].fieldsMap,
    }
}, (dispatch) => {
    return {
        //模糊查询表名称集合
        getTables: (name) => {
            dispatch({
                type: namespace + "/getTables",
                name: name
            });
        },
        getFieldsMap: (selectTables) => {
            dispatch({
                type: namespace + "/getFieldsMap",
                selectTables: selectTables
            });
        }
    }

})

class GenerateXml extends React.Component {

    state = {selectTables: [],selectFieldsMap:[],selectConditionsMap:[]}

    render() {
        return (
            <div>
                <div style={{width: "500px"}}>
                    <input ref='tableName'/>
                    <button onClick={() => this.getInputValue()}>查询</button>
                    <button onClick={() => this.props.getFieldsMap(this.state.selectTables)}>刷新</button>
                    <form method={"post"} action={"http://122.112.164.230:8080/generateXML"}>
                        <input name={"resultMap"} hidden/>
                        <input name={"conditions"} hidden/>
                        <input name={"queryFields"} hidden/>
                        <input name={"queryTables"} hidden/>
                        <input name={"simpleName"} hidden/>
                        <button onClick={() => this.generateXML()} type={"submit"}>生成xml文件</button>
                    </form>
                    <h1>查询的表名</h1>
                    <SelectTable arr={this.props.tables} put={this.putSelectTables.bind(this)}/>
                </div>
                <div>
                    {
                        this.props.fieldsMap.map((item, index) => {
                            return (
                                <div key={index} style={{
                                    width: "500px",
                                    height: "300px",
                                    margin: "10px",
                                    borderStyle: "outset",
                                    float: "left"
                                }}>
                                    <h1>
                                        {this.state.selectTables[index]}<span style={{color:"red"}}>{" as "+this.getAlias(index)}</span>
                                    </h1>
                                    <br/>
                                    {index != 0 ?
                                        <div>
                                            <span>连接方式</span>
                                            <select ref={"joinModel_"+index}>
                                                <option>--请选择--</option>
                                                <option>inner join</option>
                                                <option>left join</option>
                                                <option>right join</option>
                                            </select>
                                            <span>连接条件</span>
                                            <input ref={"joinCondition_"+index}/>
                                            <h2 >选择resultMap和select后使用的字段</h2>
                                            <SelectField arr={this.get(item)} put={this.putSelectFields.bind(this)} index={index}/>
                                        </div>
                                        :
                                        <div>
                                            <h2 >选择resultMap和select后使用的字段</h2>
                                            <SelectField arr={this.get(item)} put={this.putSelectFields.bind(this)} index={index}/>
                                        </div>
                                    }
                                    <h2>
                                        选择conditions使用的字段
                                    </h2>
                                    <SelectFieldForConditions arr={this.get(item)} put={this.putSelectConditions.bind(this)}  index={index}/>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
        );
    }

    /**
     * 获取用户输入的表名
     */
    getInputValue() {
        const tableName = this.refs.tableName.value;
        this.props.getTables(tableName);
    }

    /**
     * 从服务端返回的Fields数据中筛选出name放入集合中
     * @param item
     * @returns {[]}
     */
    get(item) {
        let arr = []
        for (let index in item) {
            arr[index] = item[index].name;
        }
        return arr;
    }

    /**
     * 将已选择的表数据从子组件传递到父组件
     * @param selectTables
     */
    putSelectTables(selectTables) {
        this.state.selectTables = selectTables;
    }

    /**
     * 将已选择的查询字段数据从子组件传递到父组件
     */
    putSelectFields(selectFields,index){
        this.state.selectFieldsMap[index]=selectFields;
    }

    /**
     * 将已选择的查询字段数据从子组件传递到父组件
     */
    putSelectConditions(selectConditions,index){
        this.state.selectConditionsMap[index]=selectConditions;
    }


    /**
     * 根据下标获取表的别名
     */
    getAlias(index) {
        if (index == 0) {
            return "a"
        } else if (index == 1) {
            return "b"
        } else if (index == 2) {
            return "c"
        } else if (index == 3) {
            return "d"
        } else if (index == 4) {
            return "e"
        } else if (index == 5) {
            return "f"
        } else {
            alert("连接查询请不要超过6张表！!!!!")
        }
    }

    /**
     * TODO   字符串生成
     * 获取conditions所需的Fields
     * this.state.selectFieldsMap是中的Fields是字符串数组，只记录每张表选取的字段名称
     * 而这里需要的是Field{name,columnName,jdbcType}集合
     */
    getConditionsFields(){
        let conditionsFields=[];
        let  selectConditionsMap=this.state.selectConditionsMap;
        for( let index1 in selectConditionsMap){
            for(let index2 in selectConditionsMap[index1]){
                conditionsFields[conditionsFields.length]=this.getFieldByName(selectConditionsMap[index1][index2],index1);
            }
        }
        return conditionsFields;
    }


    /**
     * TODO   字符串生成
     * 获取resultMap所需的Fields
     * this.state.selectFieldsMap是中的Fields是字符串数组，只记录每张表选取的字段名称
     * 而这里需要的是Field{name,columnName,jdbcType}集合
     */
    getResultMapFields(){
        let resultMapFields=[];
        let  selectFieldsMap=this.state.selectFieldsMap;
        for( let index1 in selectFieldsMap){
            for(let index2 in selectFieldsMap[index1]){
                resultMapFields[resultMapFields.length]=this.getFieldByName(selectFieldsMap[index1][index2],index1);
            }
        }
        return resultMapFields;
    }

    getFieldByName(name,num){
        let  fields=this.props.fieldsMap[num];
        let  fieldList=[];
        for(let index in fields){
            if(fields[index].name==name){
                return fields[index];
            }
        }
    }

    /**
     * TODO   字符串生成
     * 获取select后查询的字段
     */
    getQueryFields(){
        let queryFields="";
        let selectFieldMap=this.state.selectFieldsMap;
        for( let index1 in selectFieldMap){
            let alias=this.getAlias(index1);
            for(let index2 in selectFieldMap[index1]){
                queryFields=queryFields+alias+"."+selectFieldMap[index1][index2]+",";
            }
        }
        queryFields=queryFields.substring(0,queryFields.length-1);
        return queryFields;
    }

    /**
     * TODO   字符串生成
     * 获取查询表的条件信息
     */
    getQueryTables(){
        let queryTables="";
        let selectTables=this.state.selectTables;
        for(let index in selectTables){
            queryTables=queryTables+"##"+this.getJoinModel(index)+selectTables[index]+" as "+this.getAlias(index)+" "+this.getJoinCondition(index);
        }
        return queryTables;
    }
    getJoinModel(index){
        if(index==0)return "";
        let joinModel=this.refs["joinModel_"+index].value;
        return joinModel+" ";
    }
    getJoinCondition(index){
        if(index==0)return "";
        let joinCondition=this.refs["joinCondition_"+index].value;
        return  " on "+joinCondition+" ";
    }


    generateXML() {
        let resultMap=JSON.stringify(this.getResultMapFields());
        let conditions=JSON.stringify(this.getConditionsFields());
        let queryFields=this.getQueryFields();
        let queryTables=this.getQueryTables();
        let simpleName=this.props.tables[0];
        document.getElementsByName("resultMap")[0].value=resultMap;
        document.getElementsByName("conditions")[0].value=conditions;
        document.getElementsByName("queryFields")[0].value=queryFields;
        document.getElementsByName("queryTables")[0].value=queryTables;
        document.getElementsByName("simpleName")[0].value=simpleName;
    }
}

export default GenerateXml;